package com.pagoda.nerp.trade.app.quality.utils;

import com.alibaba.fastjson.JSONObject;
import com.pagoda.nerp.trade.common.CryptUtil;
import com.pagoda.nerp.trade.common.enums.ErrorCodeMappingEnums;
import com.pagoda.nerp.trade.common.exception.QualityException;
import com.pagoda.nerp.trade.common.httputil.HttpClientHelper;
import com.pagoda.nerp.trade.common.objectutil.PropertyConfigurer;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import static com.pagoda.nerp.trade.common.CryptUtil.sortMapByKey;

/**
 * Created by dell on 2016/12/29.
 */
public class InvokeQualityPartUtils {

    /**
     * 生成请求报文
     * @param param_json
     * @return
     */
    public static String formReqParam(Map param_json){
        String app_secret= PropertyConfigurer.parseStr("quality.app_secret");
        Map<String,Object> reqParam = new HashMap<String,Object>();
        reqParam.put("app_key", PropertyConfigurer.parseStr("quality.appKey"));
        reqParam.put("token", PropertyConfigurer.parseStr("quality.token"));
        reqParam.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Timestamp(System.currentTimeMillis())));
        reqParam.put("format",PropertyConfigurer.parseStr("quality.format"));
        reqParam.put("v",PropertyConfigurer.parseStr("quality.v"));
        reqParam.put("param_json", sortMapByKey(param_json));
        //加密生成签名
        reqParam.put("sign", CryptUtil.MD5sign(reqParam,app_secret));
        return JSONObject.toJSONString(reqParam);
    }

    /**
     * 调用质检平台接口
     * @param param_json
     * @param url
     * @return
     */
    public static JSONObject invokeQualityPart(Map param_json, String url){
        String resp = HttpClientHelper.invoke(url, formReqParam(param_json));
        if (resp == null) {
            throw new QualityException(ErrorCodeMappingEnums.ERROR_HTTP_REQUEST_FAIL);
        }
        return JSONObject.parseObject(resp);
    }


}
